package com.dhl.commonutils.security;

import cn.hutool.json.JSONUtil;
import com.dhl.commonutils.R;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 登录成功处理器
 *
 * @title: LoginSuccessHandler
 * @Author danghailiang
 * @Date: 2022/10/14 21:13
 * @Version 1.0
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        // 设置响应类型
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        // 获取输出流
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        String message = e.getMessage();
        if (e instanceof BadCredentialsException) {
            message = "用户名或密码错误";
        }

        R r = R.error();
        r.setMessage(message);

        // 返回数据
        outputStream.write(JSONUtil.toJsonStr(r).getBytes(StandardCharsets.UTF_8));
        // 刷新缓存
        outputStream.flush();
        // 关闭流
        outputStream.close();
    }
}
